'use strict';
const requireEx = require('yi-require');
const ObjectID = require('mongodb').ObjectID;

// const middleware = (req, res, next) => {
//
// };

module.exports = {
    open: false,
//    middleware: middleware,
    description: '添加商品到购物车',
    handler(req, res, next) {
        const doc = req.body;

        let authInfo = req.context || req.context.authInfo;
        if (!req.context || !req.context.authInfo) {
            return res.err.unauthorized();
        }
        authInfo = authInfo.authInfo;
        let userId = ObjectID(authInfo._id);

        req.mongo.collection("cart").findOne({storeId: doc.storeId, userId: userId}, (e0, r0) => {
            if (e0) return res.err.mongoError(e0);
            if (r0) {
                req.mongo.collection("cart").updateOne({_id:r0._id},{$inc:{buyCount:doc.buyCount}},(e1,r1)=>{
                    if(e1) return res.err.mongoError(e2);
                    return res.reply({code:0,message:"插入成功"});
                });
            } else {
                let cart = {
                    _id: new ObjectID(),
                    mallId: doc.mallId,
                    storeId: doc.storeId,
                    goodsId: doc.goodsId,
                    userId: userId,
                    buyCount: 1
                };
                req.mongo.collection("cart").insertOne(cart,(e2,r2)=>{
                    if(e2) return res.err.mongoError(e2);
                    return res.reply({code:0,message:"插入成功"});
                });
            }
        });

    }
};
